﻿using Common;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace T68Control.S12L_M1
{
    internal class TCPServer
    {
        public void Connect(string ip = "127.0.0.1", int port = 7920)
        {
            IPAddress ipAddress = IPAddress.Parse(ip);
            // 创建一个监听的套接字
            TcpListener server = new TcpListener(ipAddress, port);

            server.Start();
            Mylog.Info($"Server started and listening on {ipAddress}:{port}");
            // 持续监听客户端连接
            while (true)
            {
                // 接受客户端连接
                TcpClient client = server.AcceptTcpClient();
                Mylog.Info($"Connection established with {client.Client.RemoteEndPoint}");

                // 创建一个线程来处理客户端连接
                Thread clientThread = new Thread(HandleClient);
                clientThread.Start(client);
            }
        }

        public string Data { get; set; }
        private bool IsReceived;

        public void ReceiveReady()
        {
            Data = "";
            IsReceived = false;
        }

        public void WaitReceiveFinish()
        {
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < 10000; i++)
            {
                if (IsReceived)
                {
                    IsReceived = false;
                    sw.Restart();
                }
                if (sw.ElapsedMilliseconds > 500)
                {
                    break;
                }
                Thread.Sleep(10);
                i += 10;
            }
        }

        private void HandleClient(object obj)
        {
            TcpClient client = (TcpClient)obj;
            NetworkStream stream = client.GetStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            try
            {
                // 持续读取客户端发送的数据
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    IsReceived = true;
                    // 将字节数据转换为字符串
                    string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Mylog.Debug($"Received data from {client.Client.RemoteEndPoint}: {data}");
                    Data += data;
                }
            }
            catch (Exception ex)
            {
                Mylog.Error($"TCP Server Error: {ex.Message}");
            }
            finally
            {
                // 关闭连接
                stream.Close();
                client.Close();
            }
        }
    }
}